﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWMAG.Scripting.AST.ObjectModel;
using IWMAG.Scripting.Types;
using IWMAG.Scripting.AST.TerminalExpressions;
using System.Reflection;
using IWMAG.Scripting.Helpers;
using IWMAG.Scripting.Interpreter;

namespace IWMAG.Scripting.AST.Statements {
    public class ImportStatement : CodeStatement {
        public Type ClrType;
        public CodeType ClrName;
        public CodeType Alias;

        public ImportStatement(Compiler.Lexeme l, CodeType clr, CodeType alias)
            : base(l) {
            ClrName = clr;
            Alias = alias;
        }

        public ImportStatement(Compiler.Lexeme l, Type clr, CodeType alias) : base(l) {
            ClrType = clr;
            ClrName = new ReferenceType(ClrType.FullName.Split('.'));
            Alias = alias;
        }

        public override void Verify(CompileTable sym, List<Compiler.IUserInfo> error) {
        }

        public void Initialize(ScriptEngine engine, List<Compiler.IUserInfo> error) {
            if (!(ClrName is ReferenceType)) {
                SendError(error, "Import name must not be a primitive or array type.");
            } else if (ClrType == null) {
                string qualified = string.Join(".", ((ReferenceType) ClrName).Identifier);

                foreach (Assembly asm in engine.ExposedAssemblies) {
                    try {
                        ClrType = asm.GetType(qualified, true);
                        break;
                    } catch { }
                }

                if (ClrType == null) {
                    SendError(error, "Import name must be a fully qualified CLR type.");
                }
            }
        }
    }
}
